package com.sc.workorder.core.api.web;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.workorder.entity.WoWorkOrderTimeline;
import com.sc.common.util.cache.DataDictionaryUtil;
import com.sc.workorder.core.service.WoWorkOrderTimelineService;
import com.sc.common.annotations.WebApi;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sc.common.dto.WebResponseDto;
import tk.mybatis.mapper.entity.Example;
import java.util.List;

/**
 * @author: wust
 * @date: 2020-04-09 13:13:36
 * @description:
 */
@WebApi
@RequestMapping("/web/v1/WorkOrderTimelineController")
@RestController
public class WorkOrderTimelineController {
    @Autowired
    private WoWorkOrderTimelineService woWorkOrderTimelineServiceImpl;



    @RequestMapping(value = "/timelineDetail",method = RequestMethod.POST)
    public WebResponseDto timelineDetail(@RequestParam String workOrderNumber){
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        Example example = new Example(WoWorkOrderTimeline.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("workOrderNumber",workOrderNumber);
        example.setOrderByClause("id DESC");
        List<WoWorkOrderTimeline> workOrderTimelines = woWorkOrderTimelineServiceImpl.selectByExample(example);
        if(CollectionUtil.isNotEmpty(workOrderTimelines)){
            JSONArray jsonArray = new JSONArray();
            int i = workOrderTimelines.size();
            for (WoWorkOrderTimeline workOrderTimeline : workOrderTimelines) {
                String typeLabel = DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(),workOrderTimeline.getType());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("timestamp", typeLabel + " " + new DateTime(workOrderTimeline.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
                jsonObject.put("datetime", new DateTime(workOrderTimeline.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"));
                jsonObject.put("type",workOrderTimeline.getType());
                jsonObject.put("typeLabel", typeLabel);
                jsonObject.put("description",workOrderTimeline.getDescription());
                jsonArray.add(jsonObject);
            }
            responseDto.setObj(jsonArray);
        }
        return responseDto;
    }
}
